package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool JedisPool;

    @Override
    public void addSetMeal(Setmeal setmeal, Integer[] checkgroupIds) {

        setmealDao.addSetMeal(setmeal);

        Integer id = setmeal.getId();
        setSetmealAssociationCheckGroup(id,checkgroupIds);

        //图片名保存数据库后，保存图片名值redis,redis中对应的K值：SETMEAL_PIC_DB_RESOURCES
        String img = setmeal.getImg();
        JedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,img);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);

        Page<Setmeal> page = setmealDao.findSetMealByCondition(queryString);

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Setmeal> getAllSetmeal() {
        return setmealDao.getAllSetmeal();
    }

    @Override
    public Setmeal findById(int id) {


        return setmealDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {

        return setmealDao.findSetmealCount();
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    public void setSetmealAssociationCheckGroup(Integer setmeal_id,Integer[] checkgroupIds){
        for (Integer checkgroup_id : checkgroupIds) {
            HashMap<String, Integer> map = new HashMap<>();
            map.put("setmeal_id",setmeal_id);
            map.put("checkgroup_id",checkgroup_id);
            setmealDao.addSetmealAssociationCheckGroup(map);
        }
    }
}
